/*********************************************************************
 * ThreadObjectFactory.java created on Feb 3, 2010
 *
 * This file is part of Sure Tech Support Portal System. 
 * Copyright @ 2010 Sure Tech (HK) Limited. All rights reserved.
 * Sure Tech PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *********************************************************************/
package com.bizdigger.thread.pool;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.PoolableObjectFactory;

/**
 * @Author: Mac Wang
 * @Date: Feb 3, 2010 2:56:51 PM 
 * @Email: mac@suretech.com.hk
 */

public class ThreadObjectFactory implements PoolableObjectFactory {
	private Log log = LogFactory.getLog(ThreadObjectFactory.class);

	@Override
	public void activateObject(Object arg0) throws Exception {
		log.debug("activate object...");
	}

	@Override
	public void destroyObject(Object obj) throws Exception {
		if(obj instanceof WorkerThread)
		{
			WorkerThread wt = (WorkerThread)obj;
			wt.setStopped(true);
		}
	}

	@Override
	public Object makeObject() throws Exception {
		return new WorkerThread();
	}

	@Override
	public void passivateObject(Object obj) throws Exception {
		if(obj instanceof WorkerThread)
		{
			WorkerThread wt = (WorkerThread)obj;
			wt.setResult(null);	//Clean up the result of the execution
		}
	}

	@Override
	public boolean validateObject(Object obj) {
		if(obj instanceof WorkerThread)
		{
			WorkerThread wt = (WorkerThread)obj;
			if(wt.isRunning())
			{
				if(wt.getThreadGroup() == null)
					return false;
				return true;
			}
		}
		return true;
	}

}
